package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class WmNewsMaterialServiceImpl extends ServiceImpl<WmNewsMaterialMapper, WmNewsMaterial> implements WmNewsMaterialService {

    @Autowired
    WmMaterialService wmMaterialService;

    @Autowired
    FileStorageService fileStorageService;

    /**
     * 根据id删除素材
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPictre(Integer id) {
        if(id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //在数据库中查找该素材信息
        WmMaterial wmMaterial = wmMaterialService.getById(id);
        if(wmMaterial == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        int count = count(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, id));
        if(count > 1){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"素材被引用 不能删除");
        }
        //从数据库中删除
        wmMaterialService.removeById(id);
        //从oss中删除
        fileStorageService.delete(wmMaterial.getUrl());

        return ResponseResult.okResult("删除成功");
    }
}
